import * as React from "react";
import * as _ from "underscore";

import {Region} from "./region";
import {Toolbar} from "./toolbar";
import {Router} from "./router";
import {UploaderWindow} from "./uploader-window";
import {Menu} from "./menu";
import {AttachmentsBrowser} from "./attachments-browser";
import {UploaderInline} from "./uploader-inline";
import {Selection} from "./selection";
import {Button} from "./button";

export interface FrameProps {
    states: {}[];
    current?: string;
    className?: string;
    mode?: string[];
}

export interface FrameState {
    id?: string;
    title?: string;
    menu?: string;
    content?: string;
    toolbar?: string;
    router?: string;
    currentContent?: string;
}

export default class Frame extends React.Component<FrameProps, FrameState> {
    public regions: string[] = ['menu', 'title', 'content', 'toolbar', 'router'];

    constructor(props) {
        super(props);

        let state;
        if (props.current) {
            state = _.find(props['states'] || [], (state) => {
                if (state.id === props.current) {
                    return state;
                }
            });
        } else {
            state = (props['states'] || [])[0];
        }

        this.state = Object.assign({}, state || {});

        this.handleRouterChange = this.handleRouterChange.bind(this);
        this.handleMenuChange = this.handleMenuChange.bind(this);
    }

    render() {
        let {className = 'media-frame', mode = []} = this.props;

        className = 'wp-core-ui ' + className;

        mode.forEach((mode) => {
            className += ' mode-' + mode;
        });

        let regions = [];

        this.regions.forEach((name) => {
            switch (name) {
                case 'title':
                    regions.push(<Region name={name} key={name} ref={name}>{this.renderTitle()}</Region>);
                    break;
                case 'menu':
                    regions.push(<Region name={name} key={name} ref={name}>{this.renderMenu()}</Region>);
                    break;
                case 'toolbar':
                    regions.push(<Region name={name} key={name} ref={name}>{this.renderToolbar()}</Region>);
                    break;
                case 'router':
                    regions.push(<Region name={name} key={name} ref={name}>{this.renderRouter()}</Region>);
                    break;
                case 'content':
                    regions.push(<Region name={name} key={name} ref={name}>{this.renderContent()}</Region>);
                    break;
            }
        });

        return (
            <div className={className}>
                {regions}
                <div className="media-frame-uploader">{this.renderUploader()}</div>
            </div>
        );
    }

    handleTitleClick() {

    }

    renderTitle() {
        let {title} = this.state;
        return <h1 onClick={e => this.handleTitleClick()}>{title}<span className="dashicons dashicons-arrow-down"/></h1>
    }

    renderMenu() {
        let items = [];

        this.props.states.forEach((state) => {
            if (this.state.menu === state['menu']) {
                items.push({
                    name: state['id'],
                    text: state['title']
                });
            }
        });

        return <Menu items={items} className="media-menu" onClick={this.handleMenuChange} selected={this.state.id}/>
    }

    renderToolbar() {
        let mode = this.state.toolbar;
        if (mode === 'select') {
            return (
                <Toolbar primary={
                    <button type="button" className="media-button-primary">选择</button>
                }/>
            )
        } else if (mode === 'main-insert') {
            return (
                <Toolbar
                    secondary={
                        <Selection editable={true} clearable={true} attachments={[]}/>
                    }
                    primary={
                        <Button text="选择插入" style="primary" classes={['media-button-insert']}/>
                     }
                />
            )
        }
    }

    handleMenuChange(name) {
        let state =  _.find(this.props['states'] || [], (state) => {
            if (state.id === name) {
                return _.extend({}, this.state, state);
            }
        }) || {};

        state['currentContent'] = this.state.currentContent;
        console.log(state);

        this.setState(state || {});
    }

    handleRouterChange(name) {
        this.setState({
            content: name,
            currentContent: name,
        });
    }

    renderRouter() {
        let items = [
            {
                name: 'upload',
                text: '上传',
                priority: 20
            },
            {
                name: 'browse',
                text: '浏览',
                priority: 40
            }
        ];
        return <Router items={items} className="media-router" selected={this.state.currentContent || this.state.content} onClick={this.handleRouterChange}/>
    }

    renderUploader() {
        return <UploaderWindow/>
    }

    renderContent() {
        let mode = this.state.content;
        if (mode === 'browse') {
            return <AttachmentsBrowser attachments={[]}/>
        } else {
            return <UploaderInline/>
        }
    }
}

(Frame as React.ComponentClass<FrameProps>).defaultProps = {
    states: [],
    current: '',
    mode: ['select']
};
